package com.skyworth.web.admin.table.repository;

import com.skyworth.web.admin.table.model.TableModel;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 * Created by cody on 2016/8/11.
 */
public interface TableRepository extends PagingAndSortingRepository<TableModel, Long> {

    /**
     * 获取商家的所有台桌
     * @param id
     * @return
     */
    Iterable<TableModel> queryByStoreId(long id);

    /**
     * 根据服务员ID获取台桌
     * @param id
     * @return
     */
    Iterable<TableModel> queryByManagerId(long id);

    @Query("select m from TableModel m where m.storeId=?1")
    Page<TableModel> allValidTable(long store_id, Pageable pageable);

    @Modifying
    @Query("update TableModel m set m.state =0 where m.id = ?1")
    public void updateTableState(long tableId);

    @Query("SELECT CASE WHEN COUNT(tt) > 0 THEN 'true' ELSE 'false' END FROM TableModel tt WHERE tt.name = ?1")
    boolean existsByName(String name);

    @Modifying
    @Query("update TableModel m set m.state =1 where m.id = ?1")
    public void updateTableOrderState(long tableId);

    /**
     *
     * @param orderId 订单的id
     * @param state 订单对应的台桌的状态
     */
    @Modifying
    @Query("update TableModel m set m.state=?2 where m.id=(select o.tableId from OrderModel o where o.id=?1)")
    void setTableStateByOrderId(Long orderId, int state);

    @Query("SELECT CASE WHEN COUNT(tt) > 0 THEN 'true' ELSE 'false' END FROM TableModel tt WHERE tt.name = ?1 and tt.id <> ?2")
    boolean existsTable(String name, long id);

    @Query("SELECT CASE WHEN COUNT(tt) > 0 THEN 'true' ELSE 'false' END FROM TableModel tt WHERE tt.name = ?1 and tt.storeId = ?2")
    boolean existsTableByStore(String name, long store_id);
}
